package com.demo.config;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.lucene.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadPoolFactory {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolFactory.class);
    private Map<String, ExecutorService> executorServiceMap = new HashMap();
    private static ThreadPoolFactory instance = null;

    public ThreadPoolFactory() {
    }

    public static ThreadPoolFactory newInstance() {
        if (instance == null) {
            Class var0 = ThreadPoolFactory.class;
            synchronized(ThreadPoolFactory.class) {
                if (instance == null) {
                    instance = new ThreadPoolFactory();
                }
            }
        }

        return instance;
    }

    public ExecutorService add(String poolName) {
        return this.add(poolName, 10);
    }

    public ExecutorService add(String poolName, Integer poolSize) {
        ExecutorService executorService = this.getThreadPool(poolName);
        if (executorService == null) {
            executorService = Executors.newFixedThreadPool(poolSize == null ? 10 : poolSize, new NamedThreadFactory(poolName));
            this.executorServiceMap.put(poolName, executorService);
            log.info("初始化【{}】线程池完成，线程池大小【{}】", poolName, poolSize);
        }

        return executorService;
    }

    public ExecutorService getThreadPool(String poolName) {
        return (ExecutorService)this.executorServiceMap.get(poolName);
    }

    public void shutdown(String poolName) {
        ExecutorService executorService = (ExecutorService)this.executorServiceMap.get(poolName);
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            this.executorServiceMap.remove(poolName);
            log.info("移除【{}】线程池完成", poolName);
        }

    }
}